
package jwww.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/** A page produced by a Service call before headers
    have been produced.
*/
public class Page
{
  /** HTTP status.  200 or 404.
   */
  protected int    status;

  /** Effective date.  Use rfc822() to get String form.
   */
  protected Date   date;

  /** HTTP headers.
   */
  protected String headers;

  /** HTML body. May be null if method was HEAD.
   */
  protected String body = null;

  public Page()
  {}

  public Page(int status, Date date)
  {
    this.status = status;
    this.date   = date;
  }

  public Page(int status, Date date, String body)
  {
    this(status, date);
    this.body   = body;
  }

  public Page(String body)
  {
    this(200, new Date(), body);
  }

  /** Generate and cache headers based on constructor info.
   */
  public String makeHeaders()
  {
    if (headers != null)
      return headers;

    String result = "";
    result += "HTTP/1.0 " + status + " OK\r\n";
    result += "Server: GEMS\r\n";
    if (body != null)
      result += "Content-Length: " + body.length() + "\r\n";
    result += "Connection: close\r\n";
    result += "Content-Type: text/html; charset=iso-8859-1\r\n";
    result += "Date: " + rfc822() + "\r\n";

    headers = result;
    return result;
  }

  static DateFormat format =
  new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");

  /** Return date as RFC 822 String.
   */
  public String rfc822()
  {
    return format.format(date);
  }

  public static Page notFound(String query)
  {
    return new Page(404, new java.util.Date(),
                       query + " not found.");
  }
}
